package com.sh.personnel.service.impl;

import com.sh.personnel.mapper.UserInfoMapper;
import com.sh.personnel.security.util.SecurityUtil;
import com.sh.personnel.service.UserInfoService;
import com.sh.personnel.util.JwtUtil;
import com.sh.personnel.util.PwUtil;
import com.sh.personnel.vo.dto.PasswordDto;
import com.sh.personnel.vo.dto.UserInfoDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Service;

import javax.print.DocFlavor;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 林思浩
 * @date 2020/03/14 1:14
 */
@Service
public class UserInfoServiceImpl implements UserInfoService {

    @Autowired
    UserInfoMapper userInfoMapper;

    @Override
    public String getUserAvatar(String id) {
        String avatar = userInfoMapper.findUserAvatar(id);
        return avatar;
    }

    @Override
    public UserInfoDto getUserInfo(String id) {
        UserInfoDto userInfo = userInfoMapper.findUserInfo(id);
        List<String> list = new ArrayList<>();
        list.add(userInfo.getProvince());
        list.add(userInfo.getCity());
        list.add(userInfo.getDistrict());
        userInfo.setAddress(list);
        return userInfo;
    }

    @Override
    public boolean updateUserInfo(UserInfoDto userInfo) {
        List<String> address = userInfo.getAddress();
        userInfo.setProvince(address.get(0))
                .setCity(address.get(1))
                .setDistrict(address.get(2))
                .setId(SecurityUtil.getUser().getUserId());
        int result = userInfoMapper.updateUserInfo(userInfo);
        return result>0 ? true : false;
    }

    @Override
    public boolean uploadAvatar(String id, String avatar) {
        int result = userInfoMapper.updateUserAvatar(id, avatar);
        return result>0 ? true : false;
    }

    @Override
    public boolean updateEmail(String userId, String email) {
        int result = userInfoMapper.updateEmail(userId, email);
        return result>0 ? true : false;
    }

    @Override
    public boolean updatePassword(PasswordDto passwordDto) {
        passwordDto.setId(SecurityUtil.getUser().getUserId())
                .setNewPassword(PwUtil.encrypt(passwordDto.getNewPassword()));
        int result = userInfoMapper.updatePassword(passwordDto);
        return result>0 ? true : false;
    }

    @Override
    public boolean checkPassword(String password) {
        String oldPassword = userInfoMapper.findUserPasswordById(SecurityUtil.getUser().getUserId());
        return PwUtil.matches(password, oldPassword);
    }
}
